<script setup lang="ts">
import { ColumnsType } from 'ant-design-vue/es/table';
import { h } from 'vue'
const antIcons: any = inject('antIcons')
import { getLogPage, GetPageRes, updateLog, UpdateLogRes } from '@/api/log'
import { SysUser } from '@/interface/user';
import { deleteLog } from '@/api/log'
import { message } from 'ant-design-vue';
import {
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons-vue'
import { Key } from 'ant-design-vue/es/table/interface';
import { SysLogininfor } from '@/interface/log';
import dayjs, { Dayjs } from 'dayjs'
import { useGlobalStore } from '@/store/globalStore';

const columns: ColumnsType<any> = [
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    ellipsis: true,
  },
  {
    title: '返回消息',
    dataIndex: 'msg',
    key: 'msg',
  },
  {
    title: 'IP地址',
    dataIndex: 'ipaddr',
    key: 'ipaddr',
  },
  {
    title: '登陆日期',
    dataIndex: 'accessTime',
    key: 'accessTime',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    width: 150,
  },
];

const globalStore = useGlobalStore()

const data = ref<SysUser[]>([])

const contentBoxRef = ref<HTMLElement>()
const currentPage = ref<number>(1);
const size = ref<number>(10);
const total = ref<number>(0);
const isLoading = ref<boolean>(false);
const editApiLoading = ref<boolean>(false);
const editPopShow = ref<boolean>(false);
const searchValue = ref('')

const currEditDate = ref<Dayjs>()
const currEditData = reactive<SysLogininfor>({
  infoId: -1,
  userName: '',
  ipaddr: '',
  msg: '',
  status: '',
  accessTime: ''
})

const getLogs = async (isSearch = false) => {
  isLoading.value = true;
  data.value = []
  if (isSearch) {
    pageChanged(1, size.value)
    return
  }
  try {
    const { data: res }: { data: GetPageRes } = await getLogPage(currentPage.value, size.value, searchValue.value)
    currentPage.value = res.data.current
    size.value = res.data.size
    total.value = res.data.total
    //key用于选中操作
    data.value = res.data.records.map((item: any) => {
      item.key = item.infoId
      return item
    })
  } catch (error) {
    console.error(error);
  } finally {
    isLoading.value = false;
  }
}

const pageChanged = (page: number, pageSize: number) => {
  currentPage.value = page
  size.value = pageSize
  getLogs()
}

const reloadData = () => {
  getLogs()
}

const resetData = () => {
  searchValue.value = ''
  pageChanged(1, 10)
}

const deleteData = async (_e: MouseEvent, userId: number) => {
  return new Promise((resolve) => {
    deleteLog(userId.toString()).then(res => {
      if (res.data.code == 200) {
        message.success('删除成功')
        reloadData()
      } else {
        message.error(res.data.msg || '删除失败')
      }
      resolve(true)
    })
  });
}

const deleteBatchData = async () => {
  deleteLog(selectedRows.value.join(',')).then(res => {
    if (res.data.code == 200) {
      message.success('删除成功')
      selectedRows.value = []
    } else {
      message.error(res.data.msg || '删除失败')
    }
    getLogs()
  })
}

const handleEditOk = async () => {
  editApiLoading.value = true
  try {
    const { data: res }: { data: UpdateLogRes } = await updateLog({
      ...currEditData,
      accessTime: currEditDate.value?.format('YYYY-MM-DD HH:mm:ss') || currEditData.accessTime
    })
    if (res.code == 200) {
      message.success('更新成功')
      getLogs()
      editPopShow.value = false
    } else {
      message.error(res.msg || '更新失败')
    }
  } catch (error) {

  } finally {
    editApiLoading.value = false
  }
}

const editData = (data: any) => {
  editPopShow.value = true
  const { infoId, userName, ipaddr, msg, status, accessTime } = data
  currEditData.infoId = infoId
  currEditData.userName = userName
  currEditData.ipaddr = ipaddr
  currEditData.msg = msg
  currEditData.status = status
  currEditData.accessTime = accessTime
  currEditDate.value = dayjs(currEditData.accessTime, 'YYYY-MM-DD HH:mm:dd')
}

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

//当前选中行
const selectedRows = ref<Key[]>([])
const onSelectChange = (selectedRowKeys: Key[]) => {
  selectedRows.value = selectedRowKeys;
};

const tableStyle = reactive<{
  width: number,
  height: number
}>({
  width: 300,
  height: 300
})

onMounted(() => {
  getLogs()
  tableStyle.height = contentBoxRef.value?.clientHeight as number - 200
  tableStyle.width = contentBoxRef.value?.clientWidth as number
})
</script>
<template>
  <div class="box-border relative w-full h-full p-3" ref="contentBoxRef" :style="{ width: globalStore.isMobile ? 'calc(100% - 60px)' : '100%' }">
    <a-row>
      <a-col :span="24">
        <a-space class="flex flex-wrap">
          <a-input placeholder="用户名/返回消息" class="w-[230px]" v-model:value="searchValue"
            @keydown.enter="getLogs(true)" />
          <a-button type="primary" class="flex items-center bg-primary-2" :icon="h(antIcons['SearchOutlined'])"
            @click="getLogs(true)" :loading="isLoading">查询</a-button>
          <a-button class="flex items-center" :icon="h(antIcons['ReloadOutlined'])" @click="resetData">重置</a-button>
          <a-button class="flex items-center justify-center" :icon="h(antIcons['ReloadOutlined'])" shape="circle"
            @click="reloadData"></a-button>
          <a-button type="primary" class="flex items-center" danger :icon="h(antIcons['CloseOutlined'])"
            :disabled="selectedRows.length == 0" @click="deleteBatchData">删除</a-button>
        </a-space>
      </a-col>
    </a-row>
    <!-- 表格 -->
    <div class="mt-3  h-fit max-h-[647px]">
      <a-table :columns="columns" :data-source="data" :pagination="false" :loading="isLoading"
        :scroll="{ y: tableStyle.height, x: globalStore.isMobile ? 'calc(100% + 800px)' : '100%' }"
        :row-selection="{ selectedRowKeys: selectedRows, onChange: onSelectChange }">
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'sex'">
            <p>{{ text == '1' ? '男' : '女' }}</p>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="text === '0' ? 'success' : 'error'">
              {{ text === '0' ? 'success' : 'error' }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'accessTime'">
            <p>{{ text }}</p>
          </template>
          <template v-if="column.key === 'operation'">
            <a-space>
              <a-button type="primary" class="flex items-center bg-primary-2" size="small"
                @click="editData(text)">编辑</a-button>
              <a-popconfirm :title="`确定删除${text.userName}在${text.accessTime}的登录日期吗?`" ok-text="确认" cancel-text="取消"
                :okButtonProps="{ type: 'default' }" @confirm="deleteData($event, text.infoId)">
                <a-button size="small" type="primary" danger class="flex items-center text-white ">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 p-3 mt-3 bg-white border-t-[1px] z-10 dark:bg-darkBg dark:border-gray-600">
      <a-pagination v-model:current="currentPage" v-model:page-size="size" :total="total"
        :show-total="total => `总共 ${total} 条`" show-size-changer @change="pageChanged" />
    </div>

    <a-modal v-model:open="editPopShow" title="修改登陆日志" :footer="null">
      <a-form :model="currEditData" name="currEditData" @finish="handleEditOk" class="mt-5" place="left"
        @finishFailed="onFinishFailed" v-bind="{
        labelCol: { span: 4 },
        wrapperCol: { span: 24 },
      }">
        <a-form-item name="userName" label="用户名" :rules="[{ required: true }]">
          <a-input v-model:value="currEditData.userName" />
        </a-form-item>
        <a-form-item name="msg" label="返回消息" :rules="[{ required: false }]">
          <a-input v-model:value="currEditData.msg" />
        </a-form-item>
        <a-form-item name="ipaddr" label="IP地址" :rules="[{ required: false }]">
          <a-input v-model:value="currEditData.ipaddr" />
        </a-form-item>
        <a-form-item name="status" label="状态" :rules="[{ required: false }]">
          <a-switch v-model:checked="currEditData.status" checkedValue="0" unCheckedValue="1">
            <template #checkedChildren>
              <CheckOutlined />
            </template>
            <template #unCheckedChildren>
              <CloseOutlined />
            </template>
          </a-switch>
        </a-form-item>
        <a-form-item name="accessTime" label="登录日期" :rules="[{ required: false }]">
          <!-- <a-input v-model:value="currEditData.accessTime" /> -->
          <a-date-picker v-model:value="currEditDate" format="YYYY-MM-DD HH:mm:ss" show-time />
        </a-form-item>
        <a-form-item :wrapper-col="{
        offset: 17,
        span: 7
      }">
          <a-space>
            <a-button key="back" @click="editPopShow = false">取消</a-button>
            <a-button html-type="submit" type="primary" class="bg-primary-2" :loading="editApiLoading">修改</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>